// import WebSocket from 'ws'
import WebSocket, { WebSocketServer } from 'ws';
import { shell, ipcMain } from 'electron'
import path from 'path'
const ncp = require('copy-paste')



// const { exec } = require('child_process')
// import edge from 'edgelectron-edge-jse'
var edge = require("electron-edge-js");

调用amtf_dxf2 = edge.func({
  assemblyFile: 'D:/amtf/amtf_csharp/amtf_dxf2/bin/Debug/amtf_dxf2.dll', // assemblyFile为dll路径
});

export default {
  constructor(mainWindow) {
    const wss = new WebSocketServer({ port: 12111 });
    wss.on('connection', (ws) => {
      // 有客户端连接时, 打印一条日志
      // console.log(`${client} client connected`);
      // console.log(`ws client connected`);
      // 并且创建'message'监听
      // ws.on('message', (message) => {
      ws.on('message', function message(data) {
        // 直接将消息打印出来
        // console.log(data);
        yy = data.toString()
        let kk = JSON.parse(yy)
        // console.log(kk);
        switch (true) {
          case '关于amtf' in kk:
            // 打开网页
            // shell.openExternal('https://github.com');
            // kk='d:kk.txt'

            if (process.env.DEBUGGING) {
              主路径 = process.cwd()//nodejs进程的当前工作目录
              // console.log(主路径);

            } else {//发布环境
              主路径 = process.resourcesPath//资源文件夹路径路径
              // console.log(主路径);
            }
            路径 = path.join(主路径, '/其他', '关于amtf.html')
            shell.openPath(路径);
            // shell.openExternal('file://' + kk);
            break;
          case '调用amtf_dxf2' in kk:
            let arg=kk.调用amtf_dxf2
            // console.log("调用amtf_dxf2  arg",arg);
            调用amtf_dxf2(arg, function (error, result) {
                let ss = arg.split('|');
                dxf全名 = ss[0];
                计数 = ss[2];
                if (计数==1) {
                  // console.log(计数);
                  路径=path.dirname(dxf全名)
                  // console.log(路径);
                  路径 = 路径.replace(/\//g, "\\");
                  // exec('clip').stdin.end(路径)
                  ncp.copy(路径, function () {
                    // complete...
                  })
                  let 消息=JSON.stringify({'调用amtf_dxf2结果':"清空旧值"})
                  广播消息(wss, ws, 消息)
                }
                // console.log(result);

                let 消息=JSON.stringify({'调用amtf_dxf2结果':`第${计数}个： ${result}    处理完成`})
                广播消息(wss, ws, 消息)
            });
            break;
          default:
            广播消息(wss, ws, yy)
            break;
        }
      });
      ws.on('close', function close() {
        // console.log('disconnected……');
      });
    })
  }
}

function 广播消息(wss, ws, params) {
  wss.clients.forEach(function each(client) {
    if (client !== ws && client.readyState === WebSocket.OPEN) {
      client.send(params);
    }
  });
}



// export default 通信
// module.exports = 通信;
